package com.example.audiodemo.slice;

import com.example.audiodemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.SurfaceOps;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.RawFileDescriptor;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.common.Source;
import ohos.media.player.Player;

import java.util.Timer;
import java.util.TimerTask;

public class MainAbilitySlice extends AbilitySlice {

    private Player player = null;
    Text text = null;

    class VideoTimer extends EventHandler {

        public VideoTimer(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event.eventId == 0) {
                if (player != null && player.isNowPlaying()) {
                    int duration = player.getDuration();
                    int currentTime = player.getCurrentTime();
                    getUITaskDispatcher().syncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            text.setText(String.format("播放时长：%ds/总时长：%ds", currentTime / 1000, duration / 1000));
                        }
                    });
                }
            }
            updateVideoTime();
        }
    }

    VideoTimer timer = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        text = (Text)findComponentById(ResourceTable.Id_video_time);
        player = new Player(getContext());
        SurfaceProvider surfaceProvider = (SurfaceProvider)findComponentById(ResourceTable.Id_surface);
        surfaceProvider.pinToZTop(true);
        try {
            String url = "entry/resources/base/media/video.mp4";
            RawFileDescriptor fd = getContext().getResourceManager().getRawFileEntry(url).openRawFileDescriptor();
            Source source = new Source(fd.getFileDescriptor(), fd.getStartPosition(), fd.getFileSize());
            player.setSource(source);
            player.setVideoScaleType(Player.VIDEO_SCALE_TYPE_FIT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        player.setPlayerCallback(new Player.IPlayerCallback() {
            @Override
            public void onPrepared() {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onPrepared");
            }

            @Override
            public void onMessage(int i, int i1) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onMessage");
            }

            @Override
            public void onError(int i, int i1) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onError");
            }

            @Override
            public void onResolutionChanged(int i, int i1) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onResolutionChanged");
            }

            @Override
            public void onPlayBackComplete() {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onPlayBackComplete");
            }

            @Override
            public void onRewindToComplete() {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onRewindToComplete");
            }

            @Override
            public void onBufferingChange(int i) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onBufferingChange");
            }

            @Override
            public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onNewTimedMetaData");
            }

            @Override
            public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
                HiLog.debug(new HiLogLabel(0, 0, "Player"),"onMediaTimeIncontinuity");
            }
        });

        surfaceProvider.getSurfaceOps().get().addCallback(new SurfaceOps.Callback() {
            @Override
            public void surfaceCreated(SurfaceOps surfaceOps) {
                player.setVideoSurface(surfaceOps.getSurface());
                player.prepare();
                player.play();
            }

            @Override
            public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
            }

            @Override
            public void surfaceDestroyed(SurfaceOps surfaceOps) {
            }
        });

        EventRunner runner = EventRunner.create(true);
        timer = new VideoTimer(runner);
        updateVideoTime();
    }

    void updateVideoTime() {
        timer.sendEvent(
                0, 1000, EventHandler.Priority.IMMEDIATE);
    }
}
